package com.ldr.base_library.mvvm

import android.os.Bundle
import android.os.PersistableBundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.Observer
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType


/**
 * Create by ldr
 * on 2019/9/20 16:35.
 */
abstract class BaseActivity<VB: ViewBinding,VM : BaseViewModel> : AppCompatActivity(), LifecycleObserver {

    abstract val mViewModel:VM
    lateinit var binding: VB
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLayout()
        startObserve()
    }

    open fun startObserve() {
        mViewModel.mException.observe(this, Observer { it?.let { onError(it) } })
    }

    //添加布局
    private fun setLayout() {
        try {
            val cls =
                (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>
            binding = cls.getMethod("inflate", LayoutInflater::class.java)
                .invoke(null, LayoutInflater.from(this)) as VB
            setContentView(binding.root)
        } catch (e: Exception) {
            e.printStackTrace()
            throw Exception("viewBinding is error")
        }
    }
    open fun onError(e: Throwable) {}


}